package nl.maarten.docenthelp.entity.thread;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

import nl.maarten.docenthelp.manager.SessionManager;

public class ConnectThread extends Thread
{
	private ServerSocket listenSocket;
	private DatagramSocket udpSocket;
	
	private boolean running = false;
	
	private SessionManager sessionManager = SessionManager.getInstance();
	
	public ConnectThread(ServerSocket listenSocket, DatagramSocket udpSocket)
	{
		this.listenSocket = listenSocket;
		this.udpSocket = udpSocket;
	}
	
	public void run()
	{
		running = true;
		
		while(running)
		{
			try 
			{
				Socket socket = listenSocket.accept();
				sessionManager.clientConnected(socket, udpSocket);
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	public void close()
	{
		running = false;
		
		try
		{
			listenSocket.close();
			this.join();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
